package com.egao.common.module.system.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.core.Constants;
import com.egao.common.core.exception.BusinessException;
import com.egao.common.core.exception.ParameterException;
import com.egao.common.core.utils.CoreUtil;
import com.egao.common.core.web.JsonResult;
import com.egao.common.module.cooperative.constants.CooperativeProjectConstants;
import com.egao.common.module.cooperative.entity.CooperativeProjectActivityStudent;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.system.constants.CollegeMajorConstants;
import com.egao.common.module.system.entity.College;
import com.egao.common.module.system.entity.CollegeRate;
import com.egao.common.module.system.entity.Major;
import com.egao.common.module.system.mapper.CollegeMapper;
import com.egao.common.module.system.service.CollegeRateService;
import com.egao.common.module.system.service.CollegeService;
import com.egao.common.module.system.service.MajorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 学院专业服务实现类
 *
 * @author lym
 */
@Service
public class CollegeServiceImpl extends ServiceImpl<CollegeMapper, College> implements CollegeService {

    @Autowired
    private MajorService majorService;
    @Autowired
    private CollegeRateService collegeRateService;

    @Override
    public List<College> listAll(Integer xl, String keyword) {
        QueryWrapper qw = new QueryWrapper<College>()
                .eq(xl != null, "xl", xl)
                .and(!StrUtil.isBlank(keyword), i -> i.like("code", keyword).or().like("name", keyword));

        qw.orderByAsc("sort");

        return baseMapper.selectList(qw);
    }

    @Override
    public JsonResult insertCollege(College college) {
        if (college == null) {
            throw new ParameterException("参数对象为空");
        }

        if (StrUtil.isBlank(college.getCode())) {
            throw new ParameterException("编码不能为空");
        }

        if (StrUtil.isBlank(college.getName())) {
            throw new ParameterException("名称不能为空");
        }

        if (college.getXl() == null) {
            throw new ParameterException("学历不能为空");
        }

        baseMapper.insert(college);

        return JsonResult.ok("添加成功");
    }

    @Override
    public College getByCode(String code) {
        return baseMapper.selectOne(new QueryWrapper<College>()
                .eq("code", code)
                .orderByAsc("sort")
                .last("limit 1")
        );
    }

    @Override
    public College getByName(String name, String xl) {
        return baseMapper.selectOne(new QueryWrapper<College>()
                .eq("name", name)
                .eq("xl", xl)
                .orderByAsc("sort")
                .last("limit 1")
        );
    }

    @Override
    public JsonResult tree() {
        List<College> collegeList = listAll(null, "");
        List<Major> majorList = majorService.listAllNoCode("", null);

        for (College college : collegeList) {
            List<Major> children = new ArrayList<>();
            for (Major major : majorList) {
                if (college.getCode().equals(major.getCollegeCode())) {
                    children.add(major);
                }
            }

            college.setChildren(children);

            if (0 == children.size()) {
                college.setChildren(null);
            }
            majorList.removeAll(children);
        }

        if (majorList.size() > 0) {
            College college = new College();
            college.setCode("00");
            college.setName("其他");
            college.setChildren(majorList);
            collegeList.add(college);
        }

        return JsonResult.ok().setData(collegeList);
    }

    @Override
    public JsonResult importCollege(MultipartFile file, Integer yearId) {
        StringBuilder sb = new StringBuilder();

        try {
            // 读取Excel
            int startRow = 1;
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream(), 0);
            List<List<Object>> list = reader.read(startRow);

            // 进行非空和重复检查
            sb.append(CoreUtil.excelCheckBlank(list, startRow, 0));
            sb.append(CoreUtil.excelCheckRepeat(list, startRow, 0));
            if (!sb.toString().isEmpty()) {
                return JsonResult.error(sb.toString());
            }

            List<College> updateList = new ArrayList<>();
            for (List<Object> objects : list) {
                College college = new College();
                college.setName(String.valueOf(objects.get(0)));
                college.setRate5(Integer.valueOf(objects.get(1).toString()));
                college.setRate8(Integer.valueOf(objects.get(2).toString()));
                updateList.add(college);
            }

            List<College> collegeList = listAll(null, "");
            for (College college : collegeList) {
                updateList.stream().filter(update -> college.getName().equals(update.getName())).findFirst().ifPresent(update -> update.setId(college.getId()));
            }

            collegeRateService.remove(new LambdaQueryWrapper<CollegeRate>().eq(CollegeRate::getYearId, yearId));

            List<CollegeRate> collegeRateList = new ArrayList<>();
            for (College college : updateList) {
                CollegeRate collegeRate = new CollegeRate();
                collegeRate.setCollegeId(college.getId());
                collegeRate.setYearId(yearId);
                collegeRate.setRate5(college.getRate5());
                collegeRate.setRate8(college.getRate8());
                collegeRateList.add(collegeRate);
            }

            collegeRateService.saveBatch(collegeRateList);

            return JsonResult.ok("导入完成");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return JsonResult.error("导入失败");
    }
}
